// pages/home/home.js
import { Api } from '../../utils/mock/mockApi.js';
let api = new Api();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    softTo: "/pages/soft/soft",
    newsTo: "/pages/news/news",
    swiper: [], // 幻灯片array:[]
    lowPrice: [], // 低价
    propInfo: [], // 热销
    tab: [], // 相关推荐数据array:[id,name,content:[]]
    recommendId: null, // 相关推荐id,上拉加载标示
    scrollWidth: '', // 选项卡头部容器宽度
    scrollNoTag: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.dataLoad();
  },
  /**
   * 数据预加载
   */
  dataLoad: function () {
    var that = this;

    // 获取首页综合数据
    api.ajax('index', function (res) {
      that.setData({
        'lowPrice': res.lowPrice,
        'swiper': res.swiper,
        'propInfo': res.propInfo,
        'scrollNoTag': res.scrollNoTag
      });
    });
    console.log(that.data.lowPrice);
    // 获取相关推荐分类
    api.ajax('recommend', function (res) {
      for (let i = 0; i < res.recommend.length; i++) {
        res.recommend[i].content = [];
      }
      that.setData({
        'tab': res.recommend,
        'recommendId': res.recommend[0].id
      });
    })

    // 获取相关推荐内容
    api.ajax('recommendContent', function (res) {
      that.setData({
        'tab[0].content': res.content
      });
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  // 获取相关推荐类型id
  onMyEvent: function (e) {
    let that = this;
    let recommendId = e.detail.tabHeadItemId;
    that.setData({
      'recommendId': recommendId
    });
    that.recommendLoad(recommendId);
  },
  // 加载相关推荐
  recommendLoad: function (recommendId) {
    let that =this;
    let tab = that.data.tab;
    for (let i = 0; i < tab.length; i++) {
      if (tab[i].id === recommendId) {
        if (tab[i].content.length === 0) {
          api.ajax('recommendContent', (res) => {
            var variable = 'tab[' + i + '].content'
            that.setData({
              [variable]: that.data.tab[i].content.concat(res.content)
            })
          })
        }
      }
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that = this;
    let tab = that.data.tab;
    let recommendId = that.data.recommendId;
    for (let i = 0; i < tab.length; i++) {
      if (tab[i].id === recommendId) {
        api.ajax('recommendContent', (res) => {
          var variable = 'tab[' + i + '].content'
          that.setData({
            [variable]: that.data.tab[i].content.concat(res.content)
          })
        })
      }
    }
    console.log(that.data.tab);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})